package com.example.shopping_web_back.controller;

import com.example.shopping_web_back.pojo.Goods;
import com.example.shopping_web_back.pojo.GoodsImages;
import com.example.shopping_web_back.pojo.PageBean;
import com.example.shopping_web_back.pojo.Result;
import com.example.shopping_web_back.service.GoodsImagesService;
import com.example.shopping_web_back.service.GoodsService;
import com.example.shopping_web_back.utils.ThreadLocalUtil;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.Map;

//本文件主要是为了解决有关于商品的操作
@RestController
@RequestMapping("/Goods")
@Validated
public class GoodsController {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsImagesService goodsImagesService;

    private static final String CURRENT_PATH = System.getProperty("user.dir");
    private static final String IMAGE_DIR = CURRENT_PATH + "/uploads/image/goods/goodsImage";

    //得到指定id的商品的数据
    @GetMapping("/gotData")
    public Result<PageBean<Goods>> gotData(
            Integer pageNum, //当前页
            Integer pageSize //每页个数
    ) {
        PageBean<Goods> pbGoods = goodsService.getGoodsData(pageNum, pageSize);
        return Result.success(pbGoods);
    }

    @GetMapping("/gotDetailData")
    public Result<Goods> gotDetailData(@RequestHeader(name = "id")String id) {
        //得到了当前展示的一个id，则取出该id的1个商品详细信息并返回
        Goods goods = goodsService.getGoodsDataByID(id);
        return Result.success(goods);
    }

    @GetMapping("/gotDataByPage")
    public Result<PageBean<Goods>> list(
            Integer pageNum, //当前页
            Integer pageSize, //每页个数
            @RequestParam(required = false) String category //分类,非必须
    ) {
        PageBean<Goods> pbGoods = goodsService.list(pageNum, pageSize, category);
        return Result.success(pbGoods);
    }

    //添加商品
    @PostMapping("/addGoods")
    public Result addGoods(@RequestHeader(name = "Customer")String token, @RequestBody Goods goods) throws ParseException, IOException {
        Map<String, Object> map = ThreadLocalUtil.get();
        String businessName = (String)map.get("Business_name");
        //根据商家名查看是否已经有该商品上架了，如果有，那么就不能上架
        Goods searchGoods = goodsService.getGoodsDataByBusiness(businessName, goods.getTitle());
        goods.setBusiness(businessName);
        goods.setSalesNum(0);
        if(searchGoods != null) {
            return Result.error("该商品您已经上架过了");
        }
        String fileName = goods.getImage().substring(goods.getImage().lastIndexOf('/') + 1);

        File dir = new File(IMAGE_DIR);

        // 重命名fileName为newFileName
        // 先获取商品的id值
        goodsService.addNewGoods(goods);
        Goods new_goods = goodsService.getGoodsDataByBusiness(businessName, goods.getTitle());
        String newFileName = fileName.substring(0, fileName.lastIndexOf('.')) + "_" + new_goods.getId() + "_0" + fileName.substring(fileName.lastIndexOf('.'));
        File fileToRename = new File(dir, fileName);
        if (fileToRename.exists()) {
            File renamedFile = new File(dir, newFileName);
            boolean success = fileToRename.renameTo(renamedFile);
            if (!success) {
                throw new IOException("Failed to rename file to " + newFileName);
            }
        }
        new_goods.setImage("http://8.138.173.30:8080/image/goods/goodsImage/" + newFileName);
        System.out.println(new_goods);
        goodsService.updateGoods(goods.getTitle(), new_goods);
        Goods goodsGetID = goodsService.getGoodsDataByBusiness(businessName, goods.getTitle());
        goodsImagesService.addGoodsImages(goodsGetID.getId(), new_goods.getImage());
        return Result.success(goodsGetID.getId());
    }

    //下架商品
    @PostMapping("/deleteGoods")
    public Result deleteGoods(@RequestHeader(name = "Customer")String token, @RequestBody Map<String, String> params) {
        //因为前端中显示的商品是肯定没错的，因此不需要校验这个商品是否存在
        //获取商家名
        Map<String, Object> map = ThreadLocalUtil.get();
        String businessName = (String)map.get("Business_name");
        String title = params.get("title");
        goodsService.deleteGoods(title,businessName);
        return Result.success();
    }

    //根据商家名和商品名获取商品信息
    @PostMapping("getGoodsByBusiness")
    public Result<Goods> getGoodsByBusiness(@RequestHeader(name = "Customer")String token, @RequestBody Map<String, String> params) {
        //获取商家名
        Map<String, Object> map = ThreadLocalUtil.get();
        String businessName = (String)map.get("Business_name");
        String goodsName = params.get("goods_name");
        Goods goods = goodsService.getGoodsDataByBusiness(businessName, goodsName);
        return Result.success(goods);
    }

    @Data
    //存储要更新的商品信息
    public static class UpdateGoods
    {
        private String old_title;
        private Goods new_goods;
    }

    //修改商品信息
    @PostMapping("updateGoods")
    public Result updateGoods(@RequestHeader(name = "Customer")String token, @RequestBody UpdateGoods list) throws IOException, ParseException {
        //获取商家名
        Map<String, Object> map = ThreadLocalUtil.get();
        String businessName = (String)map.get("Business_name");
        String old_title = list.getOld_title();
        Goods new_goods = list.getNew_goods();
        new_goods.setBusiness(businessName);
        //根据商家名查看是否已经有该商品上架了，如果有，那么就不能上架
        if (!old_title.equals(new_goods.getTitle())) {
            Goods goods = goodsService.getGoodsDataByBusiness(businessName, new_goods.getTitle());
            if(goods != null) {
                return Result.error("该商品您已经上架过了");
            }
        }

        String fileName = new_goods.getImage().substring(new_goods.getImage().lastIndexOf('/') + 1);
        String[] parts = fileName.split("_");
        File dir = new File(IMAGE_DIR);
        if(parts.length - 1 == 3)
        {
            String number = fileName.substring(fileName.lastIndexOf('_') + 1, fileName.lastIndexOf('.'));
            if(Integer.parseInt(number) != 0)
            {
                File fileToReName = new File(dir, fileName);
                if(fileToReName.exists()) {
                    String newFileName = fileName.substring(0, fileName.lastIndexOf('.') - 1) + "0" + fileName.substring(fileName.lastIndexOf('.'));
                    File renameFile = new File(dir, newFileName);
                    boolean success = fileToReName.renameTo(renameFile);
                    if(!success) {
                        throw new IOException("Failed to rename file to " + newFileName);
                    }
                    GoodsImages oldGoodsImage = new GoodsImages(), newGoodsImage = new GoodsImages();
                    oldGoodsImage.setGoodsId(new_goods.getId());
                    oldGoodsImage.setGoodsImage(new_goods.getImage());
                    new_goods.setImage("http://8.138.173.30:8080/image/goods/goodsImage/" + newFileName);
                    newGoodsImage.setGoodsId(new_goods.getId());
                    newGoodsImage.setGoodsImage(new_goods.getImage());
                    goodsImagesService.changeGoodsImages(oldGoodsImage, newGoodsImage);
                }
            }
        }else {
            // 先获取原来商品的id值
            Goods old_goods = goodsService.getGoodsDataByBusiness(businessName, old_title);
            String newFileName = fileName.substring(0, fileName.lastIndexOf('.')) + "_" + old_goods.getId() + "_" + 0 + fileName.substring(fileName.lastIndexOf('.'));
            File fileToRename = new File(dir, fileName);
            if (fileToRename.exists()) {
                File renamedFile = new File(dir, newFileName);
                boolean success = fileToRename.renameTo(renamedFile);
                if (!success) {
                    throw new IOException("Failed to rename file to " + newFileName);
                }
                GoodsImages oldGoodsImage = new GoodsImages(), newGoodsImage = new GoodsImages();
                oldGoodsImage.setGoodsId(new_goods.getId());
                oldGoodsImage.setGoodsImage(new_goods.getImage());
                new_goods.setImage("http://8.138.173.30:8080/image/goods/goodsImage/" + newFileName);
                newGoodsImage.setGoodsId(new_goods.getId());
                newGoodsImage.setGoodsImage(new_goods.getImage());
                goodsImagesService.changeGoodsImages(oldGoodsImage, newGoodsImage);
            }
        }
        //更新数据
        goodsService.updateGoods(old_title, new_goods);
        return Result.success();
    }
}
